package cn.happiness.frog.skill.service.dto;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.SneakyThrows;
import org.apache.commons.io.IOUtils;

import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Data
@AllArgsConstructor
@NoArgsConstructor
public class Song {
	private String name;

	private String key;

	@SneakyThrows
	public static List<Song> fromPath(String dir) {
		List<Song> songs = new ArrayList<>();
		List<Path> paths = Files.list(Paths.get(dir))
				.filter(path -> path.toString().endsWith(".csv"))
				.collect(Collectors.toList());
		for (Path path : paths) {
			try (InputStream is = Files.newInputStream(path)) {
				List<String> lines = IOUtils.readLines(is, StandardCharsets.UTF_8);
				for (String line : lines) {
					String[] split = line.split(",");
					if (split.length != 2) {
						throw new RuntimeException("歌曲格式错误：" + line);
					}
					Song song = new Song(split[0], split[1]);
					songs.add(song);
				}
			}
		}
		return songs;
	}
}
